<template>
  <div class="code-editor-wrapper google-style">
    <div class="code-editor-header" v-if="showHeader">
      <div class="code-editor-language">
        <a-select 
          v-model="currentLanguage" 
          :options="editorStore.supportedLanguages" 
          :style="{ width: '120px' }"
          @change="handleLanguageChange"
          placeholder="选择语言"
          size="small"
          class="language-select"
        />
      </div>
      
      <div class="code-editor-actions">
        <a-space size="mini">
          <a-select v-model="currentTheme" :options="themes" :style="{ width: '95px' }" placeholder="主题" size="small">
            <template #prefix><icon-skin /></template>
          </a-select>
          <a-tooltip content="格式化">
            <a-button type="text" size="small" @click="formatCode">
              <icon-code />
            </a-button>
          </a-tooltip>
          <a-tooltip :content="readOnly ? '只读' : '编辑'">
            <a-button type="text" size="small" @click="toggleReadOnly">
              <icon-eye v-if="readOnly" />
              <icon-edit v-else />
            </a-button>
          </a-tooltip>
          <a-tooltip content="复制">
            <a-button type="text" size="small" @click="copyCode">
              <icon-copy />
            </a-button>
          </a-tooltip>
          <a-tooltip content="重置">
            <a-button type="text" size="small" @click="resetCode">
              <icon-refresh />
            </a-button>
          </a-tooltip>
        </a-space>
      </div>
    </div>
    <!-- :style="{ height: `${height}px` }" -->
    <div class="code-editor-content"  ref="editorContentRef">
      <MonacoEditor
        v-model="code"
        :language="currentLanguage" 
        :theme="monacoTheme"
        :readOnly="readOnly"
        :options="editorOptions"
        @editorDidMount="handleEditorMounted"
        @change="handleChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import MonacoEditor from './MonacoEditor.vue'
import * as Monaco from 'monaco-editor'
import { Message } from '@arco-design/web-vue'
import { useEditorStore } from '@/stores/editor'
import { 
  IconSkin,
  IconCode,
  IconEye,
  IconEdit,
  IconCopy,
  IconRefresh
} from '@arco-design/web-vue/es/icon'

// -------- Store --------
const editorStore = useEditorStore()

interface ThemeOption {
  label: string
  value: 'vs' | 'vs-dark' | 'hc-black' | 'hc-light'
}

// -------- Props --------
interface Props {
  modelValue: string // v-model值
  initialCode?: string // 初始默认代码，用于重置
  language?: string // 外部传入的语言，优先级高于store
  theme?: 'vs' | 'vs-dark' | 'hc-black' | 'hc-light' // 初始主题
  height?: number // 编辑器高度
  readOnly?: boolean // 是否只读
  showHeader?: boolean // 是否显示头部工具栏
  options?: Partial<Monaco.editor.IStandaloneEditorConstructionOptions> // 编辑器选项
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  initialCode: '',
  language: undefined,
  theme: 'vs', // 默认浅色主题
  height: 400,
  readOnly: false,
  showHeader: true,
  options: () => ({})
})

// -------- Emits --------
type CodeEditorEmits = {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
  (e: 'language-change', language: string): void
}
const emit = defineEmits<CodeEditorEmits>()

// -------- State --------
const code = ref(props.modelValue)
const currentLanguage = ref(editorStore.selectedLanguage)
const currentTheme = ref<'vs' | 'vs-dark' | 'hc-black' | 'hc-light'>(props.theme)
const readOnly = ref(props.readOnly)
const editorInstance = ref<Monaco.editor.IStandaloneCodeEditor | null>(null)
const editorContentRef = ref<HTMLElement | null>(null)

// -------- Themes --------
const themes: ThemeOption[] = [
  { label: '浅色', value: 'vs' },
  { label: '深色', value: 'vs-dark' }
]

// -------- Computed Properties --------
const monacoTheme = computed(() => currentTheme.value)

const editorOptions = computed<Monaco.editor.IStandaloneEditorConstructionOptions>(() => ({
  fontSize: 13,
  fontFamily: '"SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace',
  minimap: { enabled: false }, // 默认关闭 minimap
  lineNumbers: 'on',
  scrollBeyondLastLine: false,
  wordWrap: 'off',
  automaticLayout: true, // 自动布局
  glyphMargin: false,
  folding: true,
  lightbulb: {
    enabled: Monaco.editor.ShowLightbulbIconMode.Off
  },
  overviewRulerBorder: false, // 隐藏滚动条边框
  scrollbar: {
    verticalScrollbarSize: 8,
    horizontalScrollbarSize: 8,
  },
  renderLineHighlight: 'gutter',
  renderWhitespace: 'none',
  cursorSmoothCaretAnimation: 'on',
  cursorBlinking: 'smooth',
  bracketPairColorization: { enabled: true },
  ...props.options,
}))

// -------- Watchers --------
watch(() => props.modelValue, (newValue) => {
  if (newValue !== code.value) {
    code.value = newValue
  }
})

watch(() => props.language, (newValue) => {
  if (newValue && newValue !== currentLanguage.value) {
    currentLanguage.value = newValue
  }
}, { immediate: true })

watch(() => props.theme, (newValue) => {
  currentTheme.value = newValue
})

watch(() => props.readOnly, (newValue) => {
  readOnly.value = newValue
})

watch(code, (newValue) => {
  emit('update:modelValue', newValue)
})

// -------- Watch editor store selectedLanguage --------
watch(() => editorStore.selectedLanguage, (newValue) => {
  if (newValue && newValue !== currentLanguage.value) {
    currentLanguage.value = newValue;
  }
}, { immediate: true });

// -------- Event Handlers --------
const handleEditorMounted = (editor: Monaco.editor.IStandaloneCodeEditor) => {
  editorInstance.value = editor
  // 设置 Google 风格的主题
  applyGoogleTheme(editor)
}

const handleChange = (value: string) => {
  emit('change', value)
}

const handleLanguageChange = (value: string) => {
  currentLanguage.value = value
  editorStore.setSelectedLanguage(value)
  emit('language-change', value)
}

// -------- Actions --------
const formatCode = () => {
  if (editorInstance.value) {
    editorInstance.value.getAction('editor.action.formatDocument')?.run()
    Message.success('代码格式化完成')
  }
}

const toggleReadOnly = () => {
  readOnly.value = !readOnly.value
  if (editorInstance.value) {
    editorInstance.value.updateOptions({ readOnly: readOnly.value })
  }
}

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(code.value)
    Message.success('代码已复制到剪贴板')
  } catch (error) {
    Message.error('复制失败，请手动复制')
    console.error('复制失败:', error)
  }
}

const resetCode = () => {
  code.value = '' // 恢复到初始代码
}

// -------- Google Theme (Approximation) --------
const applyGoogleTheme = (editor: Monaco.editor.IStandaloneCodeEditor): void => {
  Monaco.editor.defineTheme('google-light', {
    base: 'vs', // 基于浅色主题
    inherit: true,
    rules: [
      { token: 'comment', foreground: '008000' }, // 绿色注释
      { token: 'keyword', foreground: '0000ff' }, // 蓝色关键字
      { token: 'string', foreground: 'a31515' }, // 暗红色字符串
      { token: 'number', foreground: '098658' }, // 深绿色数字
      { token: 'type', foreground: '267f99' }, // 蓝绿色类型
      { token: 'identifier', foreground: '000000' }, // 黑色标识符
      { token: 'delimiter', foreground: '000000' }, // 黑色分隔符
      // ... 可以根据需要添加更多规则
    ],
    colors: {
      'editor.foreground': '#202124', // 主要文字颜色
      'editor.background': '#ffffff', // 背景色
      'editorCursor.foreground': '#1a73e8', // 光标颜色 (Google 蓝色)
      'editor.lineHighlightBackground': '#f1f3f4', // 当前行高亮
      'editorLineNumber.foreground': '#5f6368', // 行号颜色
      'editorLineNumber.activeForeground': '#1a73e8', // 当前行号颜色
      'editor.selectionBackground': '#d2e3fc', // 选中区域背景
      'editorWhitespace.foreground': '#cccccc', // 空格颜色
      'editorIndentGuide.background': '#e0e0e0', // 缩进线
      'editorIndentGuide.activeBackground': '#c0c0c0',
      // ... 其他颜色配置
    },
  });
  // 默认使用浅色主题
  currentTheme.value = 'vs' // 设置默认值，或者可以根据系统主题选择
  // Monaco.editor.setTheme('google-light') // 暂时不默认设置，允许用户选择
}

// -------- Lifecycle --------
onMounted(() => {
  // 如果外部没有传入 language prop，则使用 store 中的语言
  if (!props.language) {
    currentLanguage.value = editorStore.selectedLanguage
  }
});

// -------- Expose --------
defineExpose({
  formatCode,
  getEditor: (): Monaco.editor.IStandaloneCodeEditor | null => editorInstance.value,
  getValue: (): string => code.value,
  setValue: (value: string): void => {
    code.value = value
  },
  resetCode,
})
</script>

<style scoped>
.code-editor-wrapper.google-style {
  border: 1px solid #dadce0; /* Google 风格边框 */
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff; /* 白色背景 */
  box-shadow: 0 1px 2px 0 rgba(60, 64, 67, .3), 0 1px 3px 1px rgba(60, 64, 67, .15);
  transition: box-shadow .3s ease-in-out;
}

.code-editor-wrapper.google-style:focus-within {
   box-shadow: 0 1px 3px 0 rgba(60, 64, 67, .3), 0 4px 8px 3px rgba(60, 64, 67, .15);
}

.code-editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 12px;
  border-bottom: 1px solid #e8eaed; /* 浅灰色分割线 */
  background-color: #f8f9fa; /* 头部浅灰色背景 */
  min-height: 36px;
}

.code-editor-language .language-select {
  font-size: 13px;
}

.code-editor-actions .arco-space {
  align-items: center;
}

.code-editor-actions .arco-btn-text {
  color: #5f6368; /* Google 图标颜色 */
  font-size: 16px; /* 增大图标按钮大小 */
}

.code-editor-actions .arco-btn-text:hover {
  background-color: rgba(60, 64, 67, .08);
}

.code-editor-actions .arco-select {
  font-size: 13px;
}

.code-editor-content {
  width: 100%;
  /* MonacoEditor 会自动处理高度和滚动 */
  height: 100%;
}

/* 微调 Select 样式 */
:deep(.arco-select-view) {
  padding: 0 8px;
}

:deep(.arco-select-view-value) {
  color: #1a73e8;
  font-weight: 500;
}

:deep(.arco-select-dropdown-option-selected) {
  color: #1a73e8;
  font-weight: 500;
  background-color: #e8f0fe;
}

:deep(.arco-select-dropdown-option:hover) {
  background-color: #f1f3f4;
}
</style> 